package com.base.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * 实例化redis的各种数据操作对象
 * @author Administrator
 *
 */
@Service("redisService")
public class RedisTemplateService {
	@Autowired
	private  RedisTemplate<String, Object> redisTemplate; 
	/**
	 * 序列化redisTemplate对象
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public RedisTemplate<String, Object> redisTemplateSerialize(){
		 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();  
	     redisTemplate.setKeySerializer(new StringRedisSerializer()); 
	     redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 
	     redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
	     redisTemplate.afterPropertiesSet();
	     return redisTemplate;  
		
	}
	 /** 
     * 实例化 HashOperations 对象,可以使用 Hash 类型操作 
     */  
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public HashOperations<String, String, Object> hashOperations() {  
    	redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
    	redisTemplate.afterPropertiesSet();
    	return redisTemplate.opsForHash();  
    }  
  
    /** 
     * 实例化 ValueOperations 对象,可以使用 String 操作 
     */  
    public ValueOperations<String, Object> valueOperations() {  
    	redisTemplate.setValueSerializer(new StringRedisSerializer());
    	redisTemplate.afterPropertiesSet();
        return redisTemplate.opsForValue();  
    }  
  
    /** 
     * 实例化 ListOperations 对象,可以使用 List 操作 
     */  
	public ListOperations<String, Object> listOperations() {  
    	redisTemplate.setValueSerializer(new StringRedisSerializer());
    	redisTemplate.afterPropertiesSet();
        return redisTemplate.opsForList();  
    }  
  
    /** 
     * 实例化 SetOperations 对象,可以使用 Set 操作 
     */  
    public SetOperations<String, Object> setOperations() {  
    	redisTemplate.setValueSerializer(new StringRedisSerializer());
    	redisTemplate.afterPropertiesSet();
        return redisTemplate.opsForSet();  
    }  
  
    /** 
     * 实例化 ZSetOperations 对象,可以使用 ZSet 操作 
     */  
    public ZSetOperations<String, Object> zSetOperations() {  
        return redisTemplate.opsForZSet();  
    }  
}
